import { Injectable } from '@angular/core';
import { Effect, Actions, ofType } from '@ngrx/effects';
import { of } from 'rxjs/observable/of';
import { catchError, map, mergeMap } from 'rxjs/operators';

import { PoisActionTypes, LoadPois, LoadPoisSuccess, LoadPoisFail } from '../actions';

import { RestapiAmapService } from '../../../ngx-ol/services';
import { Poi } from '../../../ngx-ol/models';

@Injectable()
export class PoisEffects {

    constructor(
        private action$: Actions,
        private restapi: RestapiAmapService
    ) {}

    @Effect()
    loadPois$ = this.action$
        .pipe(
            ofType(PoisActionTypes.LOAD_POIS),
            mergeMap((action: LoadPois) => {
                return this.restapi.placeText(action.payload).pipe(
                    map((pois: Poi[]) => new LoadPoisSuccess(pois)),
                    catchError(error => of(new LoadPoisFail(error)))
                );
            })
        );
}